package com.sjzs.web.action;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.opensymphony.xwork2.ActionContext;
import com.sjzs.web.common.BaseAction;
import com.sjzs.web.common.GlobalNames;
import com.sjzs.web.dao.User00Dao;
import com.sjzs.web.mail.GmailSender;
import com.sjzs.web.mail.MailCofing;
import com.sjzs.web.mail.MailInfo;
import com.sjzs.web.mail.WithAttachmentMessage;
import com.sjzs.web.po.User00;
import com.sjzs.web.po.User01;
import com.sjzs.web.util.Arithmetic;
import com.sjzs.web.util.ConfigUtil;
import com.sjzs.web.util.DateUtil;
import com.sjzs.web.util.MD5Encode;

/**
 * @author acer
 * @date 2013-7-18 下午05:07:10
 */
public class User00Action extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	private User00Dao user00Dao;
	private User00 user;
	private User01 user01;
	private String status;
	private String info;

	/**
	 * 用户登录方法
	 * 
	 * @return
	 */
	public String userLogin() {
		user.setZhmm00(MD5Encode.MD5(user.getZhmm00()));
		//System.out.println(user.getZhmm00());
		user = user00Dao.userLogin(user.getZhm000(), user.getZhmm00());
		String jhflg = ConfigUtil.getInstance().getProperties("jhgl");
		String lock = ConfigUtil.getInstance().getProperties("lock");
		if (user == null) {
			// 用户名 密码错误
			status = "y";
			return "again";
		} else if ("y".equals(jhflg) && "000".equals(user.getSfjh00())) {
			// 账户未激活
			status = "j";
			return "again";
		} else if ("y".equals(lock) && "001".equals(user.getZhs000())) {
			// 账户被锁
			status = "l";
			return "again";
		} else {
			// 成功			
			// 更新上次登录时间
			user.setScdlsj(DateUtil.dateToString("yyyy-MM-dd HH:mm:ss",
					new Date()));
			user00Dao.updateByUser(user);
			//把用户信息写到session
			ActionContext actionContext = ActionContext.getContext();
	        Map session = actionContext.getSession();
	        session.put(GlobalNames.CURUSER, user);
			//super.getRequest().getSession().setAttribute(GlobalNames.CURUSER, user);		
			// 写登录日志?
			status = "n";
			return SUCCESS;
		}
	}

	/**
	 * 用户注册方法
	 * 
	 * @return
	 */
	public String register() {
		//HttpServletRequest request = getRequest();
		// String parm=getParameterString(request);
		// HashMap<String,String[]> properties = new
		// HashMap<String,String[]>(request.getParameterMap());
		// Set set=properties.entrySet();
		// Iterator it = set.iterator();
		// while (it.hasNext()) {
		// Map.Entry entry = (Entry)it.next();
		// String key = (String) entry.getKey();
		// String value = ((String[])entry.getValue())[0];
		// System.out.println(key+"--"+value);
		// }
		// Map map = request.getParameterMap();
		user.setZhmm00(MD5Encode.MD5(user.getZhmm00()));
		user00Dao.saveUser(user);
		// 发送邮件
		sendMail(user.getYxdz00(), user.getZhm000());
		return SUCCESS;
	}

	/**
	 * 更新用户信息方法
	 * 
	 * @return
	 */
	public String updateUser() {
		return null;
	}

	/**
	 * 根据账户名查找用户
	 * 
	 * @return
	 * @throws IOException
	 */
	public String queryUserByZhm() throws IOException {
		HttpServletRequest request = getRequest();
		//HttpServletResponse response = getResponse();
		// System.out.println(user.getZhm000());
		String userName = request.getParameter("userName");
		user = user00Dao.queryUserByZhm00(userName);
		if (user == null) {
			status = "y";
			info = "用户名可用!";
		} else {
			status = "n";
			info = "用户名已经存在!";
		}
		// JSONObject json = new JSONObject();
		// json.accumulate("status", "n");
		// json.accumulate("info", "用户名已经存在!");
		// response.getWriter().write("status:'n'");
		// response.getWriter().print(json);
		return "success";
	}
	/**
	 * 检查昵称
	 * @return
	 * @throws IOException
	 */
	public String queryUserByNC() throws IOException {
		HttpServletRequest request = getRequest();
		//HttpServletResponse response = getResponse();
		// System.out.println(user.getZhm000());
		String usernc = request.getParameter("usernc");
		user = user00Dao.queryUserByNC(usernc);
		if (user == null) {
			status = "y";
			info = "此昵称可用!";
		} else {
			status = "n";
			info = "此昵称已经存在!";
		}
		// JSONObject json = new JSONObject();
		// json.accumulate("status", "n");
		// json.accumulate("info", "用户名已经存在!");
		// response.getWriter().write("status:'n'");
		// response.getWriter().print(json);
		return "success";
	}

	/**
	 * 邮箱激活
	 * 
	 * @return
	 */
	public String activate() {
		String userName = getRequest().getParameter("Key");
		String timeStr = getRequest().getParameter("T");
		// 解密
		Arithmetic.getKey(GlobalNames.KEY);
		userName = Arithmetic.getDesString(userName);
		timeStr = Arithmetic.getDesString(timeStr);
		// 这里判断激活时间是否过期
		Date old = DateUtil.string14ToDate(timeStr);
		Date ndate = DateUtil.getDateAfter(old, GlobalNames.JHGQSJ);
		if (new Date().after(ndate)) {
			// 超过了15天 要重新发邮件激活

		}
		user = user00Dao.queryUserByZhm00(userName);
		if (user == null) {
			return ERROR;
		} else {
			user.setSfjh00("001");
			user00Dao.updateByUser(user);
			return SUCCESS;
		}
	}

	/**
	 * 
	 * @param mailAddress
	 *            要发送的邮箱地址
	 * @return
	 */
	public String sendMail(String mailAddress, String userName) {
		String msg = "";
		try {
			// 发送邮件
			GmailSender sender = new GmailSender();
			Session session = sender.createSession("smtp");
			String href = getRequest().getScheme() + "://"
					+ getRequest().getServerName() + ":"
					+ getRequest().getServerPort()
					+ getRequest().getContextPath();
			// 加密发送信息
			Arithmetic.getKey(GlobalNames.KEY);
			// 获取加密的密文
			String strEnc = Arithmetic.getEncString(userName);
			// 当前时间
			String time = DateUtil.dateToString14(new Date());
			String timeEnc = Arithmetic.getEncString(time);
			String param = "/system/activate.shtml?Key=";
			href = href + param + strEnc + "&T=" + timeEnc;
			String content = "点击此链接进行邮箱激活:".concat("<a href='" + href + "'>"
					+ href + "</a>");
			String from = MimeUtility.encodeText(MailCofing.YXMC) + " <"
					+ MailCofing.YXDZ + ">";
			MailInfo info = new MailInfo(from, mailAddress, "IOU邮箱激活", content);
			MimeMessage mail = new WithAttachmentMessage().createMessage(info,
					session);
			sender.sendMail(session, mail);
			msg = "success";
		} catch (Exception e) {
			System.out.println(e);
			if (e.getMessage().equals("Invalid Addresses")) {
				// LOGGER.error("发送邮件失败，收件人邮箱地址不存在： " + e);
				msg = "not_exist";
			} else {
				// LOGGER.error("发送邮件失败：" + e);
				msg = "error";
			}
		} finally {
			return SUCCESS;
		}
	}
	/**
	 * 跳转到会员登录界面
	 * @return
	 */
	public String toMemberLogin(){
		return SUCCESS;
	}	
	
	public String toMemberPerson(){
		//获取用户信息
		//把用户信息写到session
        this.user = super.getUser00();
        this.user = this.user00Dao.queryUserByDevuid(user.getDevuid());
        this.user01 = this.user00Dao.queryUser01ByDevuid(user.getDevuid());
		return SUCCESS;
	}
	/**
	 * 保存会员信息
	 */
	public void saveUser(){
		User00 user00 = this.user00Dao.queryUserByDevuid(user.getDevuid());
		user00.setNc0000(user.getNc0000());
		user00Dao.updateByUser(user00);		
		user01.setDevuid(user.getDevuid());
		user00Dao.updateByUser01(user01);		
	}

	public User00Dao getUser00Dao() {
		return user00Dao;
	}

	public void setUser00Dao(User00Dao user00Dao) {
		this.user00Dao = user00Dao;
	}

	public User00 getUser() {
		return user;
	}

	public void setUser(User00 user) {
		this.user = user;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public User01 getUser01() {
		return user01;
	}

	public void setUser01(User01 user01) {
		this.user01 = user01;
	}
}
